package com.atguigu.tingshu.live.api;

import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.live.util.WebSocketLocalContainerUtil;
import com.atguigu.tingshu.model.live.FromUser;
import com.atguigu.tingshu.model.live.SocketMsg;
import com.atguigu.tingshu.model.user.UserInfo;
import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@ServerEndpoint(value = "/api/websocket/{liveRoomId}/{token}")
public class WebSocketApiController {
    private static StringRedisTemplate stringRedisTemplate;

    @Autowired
    private void setStringRedisTemplate(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }


    @OnOpen
    public void onOpen(Session session,
                       @PathParam("liveRoomId") Long liveRoomId,
                       @PathParam("token") String token) {
        //从redis中获取用户信息
        String key = RedisConstant.USER_LOGIN_KEY_PREFIX + token;
        String userinfoJson = stringRedisTemplate.opsForValue().get(key);
        UserInfo userInfo = JSON.parseObject(userinfoJson, UserInfo.class);
        Long userId = userInfo.getId();
        //向WebSocketLocalContainerUtil对象中的map存储数据
        WebSocketLocalContainerUtil.addSession(userId,session);
        //创建FromUser对象
        FromUser fromUser = new FromUser();
        fromUser.setUserId(userId);
        fromUser.setNickname(userInfo.getNickname());
        fromUser.setAvatarUrl(userInfo.getAvatarUrl());
        WebSocketLocalContainerUtil.addFromUser(userId,fromUser);

        WebSocketLocalContainerUtil.addUserIdToLiveRoom(liveRoomId,userId);
        //构建消息对象
        SocketMsg socketMsg = WebSocketLocalContainerUtil.buildSocketMsg(liveRoomId, fromUser, SocketMsg.MsgTypeEnum.JOIN_CHAT, "欢迎" + fromUser.getNickname() + "加入直播间");
        //发送消息
        WebSocketLocalContainerUtil.sendMsg(socketMsg);


    }

    @OnClose
    public void onClose(Session session,
                        @PathParam("liveRoomId") Long liveRoomId,
                        @PathParam("token") String token) {
        //从redis中获取用户信息
        String key = RedisConstant.USER_LOGIN_KEY_PREFIX + token;
        String userinfoJson = stringRedisTemplate.opsForValue().get(key);
        UserInfo userInfo = JSON.parseObject(userinfoJson, UserInfo.class);
        Long userId = userInfo.getId();
        //删除session
        WebSocketLocalContainerUtil.removeSession(userId);
        FromUser fromUser = WebSocketLocalContainerUtil.getFromUser(userId);
        //删除fromUser
        WebSocketLocalContainerUtil.removeFromUser(userId);
        //删除uUserIdToLiveRoom
        WebSocketLocalContainerUtil.removeUserIdToLiveRoom(liveRoomId,userId);

        //构建消息对象
        SocketMsg socketMsg = WebSocketLocalContainerUtil.buildSocketMsg(liveRoomId, fromUser, SocketMsg.MsgTypeEnum.JOIN_CHAT,   fromUser.getNickname() + "退出直播间");
        //发送消息
        WebSocketLocalContainerUtil.sendMsg(socketMsg);

    }

    @OnMessage
    public void onMessage(Session session,String message){
        //把客户端传递过来的消息发送给当前直播间的用户
        SocketMsg socketMsg = JSON.parseObject(message, SocketMsg.class);

        if (!socketMsg.getMsgType().equals("0")) {
            WebSocketLocalContainerUtil.sendMsg(socketMsg);
        }
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        log.info("用户{}连接异常", session.getId());
        throwable.printStackTrace();
    }
}
